package com.rotten;

import imageLoader.DrawableManager;

import java.io.InputStream;
import java.net.URL;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Set;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

/*
 * E nesta classe onde sao apresentados os resultados das pesquisas efectuadas * 
 */

public class Rotten extends Activity {
	
	Client client = new Client();
	public static Hashtable<Integer, Movie> results = new Hashtable<Integer, Movie>();
	private Movie mov = new Movie();
	private EditText nova_pesquisa;
	private int pag_actual = 1;	
	public static String pesquisa = "toy story";
	DrawableManager draw = new DrawableManager();
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //full screen
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                                WindowManager.LayoutParams.FLAG_FULLSCREEN); 
        
        Bundle extras = getIntent().getExtras(); 
        if(extras !=null)
        {
        pag_actual = extras.getInt("pagina");
        pesquisa = extras.getString("pesquisa");
        } 
                
        setContentView(R.layout.search_movies); 
        
        actualizaPesquisa(pesquisa);
        
        //botao de nova pesquisa
        nova_pesquisa = (EditText) findViewById(R.id.pesquisa);
        Button b = (Button) findViewById(R.id.nova_pesquisa);
        b.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
            	pag_actual = 1;
            	actualizaPesquisa(nova_pesquisa.getText().toString());  	
            }
        });
	}
    
    
    public void actualizaPesquisa(final String pesquisa){
    	
    	//Envia o pedido ao servidor
        String json = client.Search_Movies(pesquisa, pag_actual);
        results = client.parse_searchResults(json);  
        int total_movies = client.getTotalMovie(json);
       
        //Trata do layout
        LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout2);
        layout.removeAllViews();  
        
        //parmetros do xml
        Log.v("total:", total_movies+"");
        TextView p = (TextView) findViewById(R.id.textView2);
        p.setText(pesquisa + " (" + total_movies + ")"); 
        p.setMaxLines(1);
                             
		Set<Integer> set = results.keySet();
		Iterator<Integer> itr = set.iterator();
		while (itr.hasNext()){
			
			Integer id = itr.next();
			mov = results.get(id);
			
			// cria o layout principal (img + texto 1 + texto2)
			final LinearLayout l1 = new LinearLayout(this);
			l1.setOrientation(LinearLayout.HORIZONTAL);
			
			// cria a imagem
			ImageView img = new ImageView(this);
			img.setId(mov.getId());
			img.setClickable(true);
		  	int mov_selected = img.getId();
		  	final int m2 = mov_selected;
		  	img.setOnClickListener(new View.OnClickListener() {
	             public void onClick(View v) {
	            	 //l1.setBackgroundColor(Color.LTGRAY);
	            	 //Comeca uma nova actividade
	            	 Intent i = new Intent(Rotten.this, Movieprofile.class);
	            	 i.putExtra("movie", m2); //passa o filme como argumento
	                 startActivity(i);
	                 
	             }
			});
			
			img.setLayoutParams(new GridView.LayoutParams(63, 90));  //tamanho da imagem
			//img.setBackgroundDrawable(getImag(mov.getPoster_thumbnail()));
			draw.fetchDrawableOnThread(mov.getPoster_thumbnail(), img);
			// cria o layout secundario (texto 1 + texto2)
			LinearLayout l2 = new LinearLayout(this);
			l2.setOrientation(LinearLayout.VERTICAL);

			// texto 1 -titulo
			String titulo = mov.getTitle();
			//if(titulo.length()>28) titulo = titulo.substring(0, 28);
			titulo += " (" + mov.getYear() + ")";
			TextView title = new TextView(this);
			title.setText(titulo);
			title.setTextSize(18);
			title.setTextColor(Color.BLACK);
			title.setPadding(10,0,0,0);

			// texto 2 - info
			
			String info;
			if(mov.getCritics_score()<0) info = "No Reviews Yet";
			else info = mov.getCritics_score() +"%";
			info += " - " + mov.getAudience_score() + "%";
			TextView detail = new TextView(this);
			detail.setText(info);
			detail.setTextSize(16);
			detail.setTextColor(Color.BLACK);
			detail.setPadding(10, 0,0,0);

			l1.setOnClickListener(new View.OnClickListener() {
	             public void onClick(View v) {
	            	 l1.setBackgroundColor(Color.LTGRAY);
	            	 //Comeca uma nova actividade
	            	 Intent i = new Intent(Rotten.this, Movieprofile.class);
	            	 i.putExtra("movie", m2); //passa o filme como argumento
	                 startActivity(i);
	                 
	             }
			});
						
			l2.addView(title);
			l2.addView(detail);
			l1.addView(img);
			l1.addView(l2);
			layout.addView(l1);
			
			}
		
		//se ja estive na proxima pagina		
		if(pag_actual > 1){
			Button less = new Button(this);
			less.setOnClickListener(new View.OnClickListener() {
	             public void onClick(View v) {	            	
	            	 pag_actual--;
	            	//Comeca uma nova actividade
	            	 Intent i = new Intent(Rotten.this, Rotten.class);
	            	 i.putExtra("pagina", pag_actual);
	            	 i.putExtra("pesquisa", pesquisa);
	                 startActivity(i);
	             }
			});			
			less.setText("Previous Page");
			layout.addView(less);
		}
		
		//se ainda tiver mais resutados para ver adiciona um botao "more"			
		if(total_movies > Client.page_limit){
			Button more = new Button(this);
			more.setOnClickListener(new View.OnClickListener() {
	             public void onClick(View v) {	            	
	            	 pag_actual++;
	            	//Comeca uma nova actividade
	            	 Intent i = new Intent(Rotten.this, Rotten.class);
	            	 i.putExtra("pagina", pag_actual);
	            	 i.putExtra("pesquisa", pesquisa);
	                 startActivity(i);
	             }
			});			
			more.setText("More Results");
			layout.addView(more);			
						
		}   	
    }
    
  //Menu
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu, menu);
        return true;
    }
    
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.home:  {
            	 Intent i = new Intent(Rotten.this, Main.class);
                 startActivity(i);
            	 break;
            }
            
            case R.id.refresh:  {
            	Intent i = new Intent(Rotten.this, Rotten.class);
            	i.putExtra("pagina", pag_actual);
            	i.putExtra("pesquisa", pesquisa);
            	startActivity(i);
           	 break;
           }
            
            case R.id.favoritos:{
            	Intent i = new Intent(Rotten.this, List_favorites.class);
                startActivity(i);	 
            	break;
            }
            
            case R.id.sair:{
            	System.exit(0);
            	break;
            }
        }
        return true;
    }
    
    
    
    
    //devolve uma imagem a partir de um link (URL)
    public static Drawable getImag(String link){
    	Object content = null;
        try{
          URL url = new URL(link);
          content = url.getContent();
        }
          catch(Exception ex)
        {
            ex.printStackTrace();
        }
        InputStream is = (InputStream)content;
        Drawable image = Drawable.createFromStream(is, "src");
        return image;
    }
}
